<script setup lang="ts">
import { computed, ref } from 'vue';

import {
  BankOutlined,
  BookOutlined,
  CrownOutlined,
  FireOutlined,
  SendOutlined,
  TrophyOutlined,
} from '@ant-design/icons-vue';
import dayjs from 'dayjs';

import { historicalEvents } from '../../../mock/zhu-dynasty/members';

const chatInput = ref('');
const chatMessages = ref([
  {
    id: 1,
    role: 'assistant',
    content: '您好，我是朱氏家族AI史官，可以为您解答关于家族历史的任何问题。',
  },
]);

const quickQuestions = [
  '朱元璋如何建立明朝？',
  '靖难之役的经过？',
  '永乐迁都的原因？',
  '明朝藩王制度是什么？',
];

const sortedEvents = computed(() =>
  [...historicalEvents].sort(
    (a, b) => new Date(a.date).getTime() - new Date(b.date).getTime(),
  ),
);

function formatDate(date: string) {
  return dayjs(date).format('YYYY年MM月DD日');
}

function getEventColor(importance: string) {
  const colors: Record<string, string> = {
    critical: 'red',
    major: 'blue',
    normal: 'gray',
  };
  return colors[importance] || 'gray';
}

function getImportanceColor(importance: string) {
  const colors: Record<string, string> = {
    critical: 'red',
    major: 'orange',
    normal: 'default',
  };
  return colors[importance] || 'default';
}

function getImportanceText(importance: string) {
  const texts: Record<string, string> = {
    critical: '重大事件',
    major: '重要事件',
    normal: '一般事件',
  };
  return texts[importance] || importance;
}

function getTypeText(type: string) {
  const texts: Record<string, string> = {
    political: '政治',
    military: '军事',
    cultural: '文化',
    governance: '治理',
    ceremony: '礼仪',
  };
  return texts[type] || type;
}

function getEventIcon(type: string) {
  const icons: Record<string, any> = {
    political: BankOutlined,
    military: FireOutlined,
    cultural: BookOutlined,
    governance: CrownOutlined,
    ceremony: TrophyOutlined,
  };
  return icons[type] || BookOutlined;
}

function sendMessage() {
  if (!chatInput.value.trim()) return;

  chatMessages.value.push({
    id: Date.now(),
    role: 'user',
    content: chatInput.value,
  });

  // Mock AI 回复
  setTimeout(() => {
    chatMessages.value.push({
      id: Date.now() + 1,
      role: 'assistant',
      content: `关于"${chatInput.value}"，根据史料记载... (这是Mock回复，实际会调用AI接口)`,
    });
  }, 1000);

  chatInput.value = '';
}

function askQuestion(q: string) {
  chatInput.value = q;
  sendMessage();
}
</script>

<template>
  <div class="archive-page">
    <a-card title="📜 史官档案 · 历史大事记">
      <a-timeline mode="left">
        <a-timeline-item
          v-for="event in sortedEvents"
          :key="event.id"
          :color="getEventColor(event.importance)"
        >
          <template #label>
            {{ formatDate(event.date) }}
          </template>
          <template #dot>
            <component :is="getEventIcon(event.type)" style="font-size: 16px" />
          </template>
          <a-card size="small" hoverable>
            <template #title>
              <a-space>
                <span>{{ event.title }}</span>
                <a-tag :color="getImportanceColor(event.importance)">
                  {{ getImportanceText(event.importance) }}
                </a-tag>
                <a-tag>{{ getTypeText(event.type) }}</a-tag>
              </a-space>
            </template>
            <p>{{ event.description }}</p>
            <a-divider style="margin: 12px 0" />
            <a-space>
              <span>📍 地点: {{ event.location }}</span>
              <span>👥 参与者: {{ event.participants.length }} 人</span>
              <a-button type="link" size="small" v-if="event.onChainHash">
                链上存证: {{ event.onChainHash.substring(0, 10) }}...
              </a-button>
            </a-space>
          </a-card>
        </a-timeline-item>
      </a-timeline>
    </a-card>

    <!-- AI 史官对话 -->
    <a-card title="🤖 AI 史官 · 智能问答" style="margin-top: 16px">
      <div class="ai-chat">
        <div class="chat-messages">
          <div
            v-for="msg in chatMessages"
            :key="msg.id"
            class="message"
            :class="[msg.role]"
          >
            <a-avatar
              v-if="msg.role === 'assistant'"
              style="background: #1890ff"
            >
              史
            </a-avatar>
            <div class="message-content">{{ msg.content }}</div>
            <a-avatar v-if="msg.role === 'user'" style="background: #52c41a">
              我
            </a-avatar>
          </div>
        </div>
        <div class="chat-input">
          <a-input
            v-model:value="chatInput"
            placeholder="问问史官关于朱氏家族的历史..."
            @press-enter="sendMessage"
          >
            <template #suffix>
              <a-button type="text" @click="sendMessage">
                <SendOutlined />
              </a-button>
            </template>
          </a-input>
        </div>
        <div class="quick-questions">
          <a-tag
            v-for="q in quickQuestions"
            :key="q"
            @click="askQuestion(q)"
            style="margin: 4px; cursor: pointer"
          >
            {{ q }}
          </a-tag>
        </div>
      </div>
    </a-card>
  </div>
</template>

<style scoped lang="scss">
.archive-page {
  .ai-chat {
    .chat-messages {
      max-height: 400px;
      padding: 16px;
      margin-bottom: 16px;
      overflow-y: auto;
      background: #fafafa;
      border-radius: 8px;

      .message {
        display: flex;
        gap: 12px;
        margin-bottom: 16px;

        &.user {
          flex-direction: row-reverse;

          .message-content {
            color: white;
            background: #1890ff;
          }
        }

        &.assistant .message-content {
          background: white;
        }

        .message-content {
          max-width: 70%;
          padding: 12px;
          border-radius: 8px;
        }
      }
    }

    .chat-input {
      margin-bottom: 8px;
    }

    .quick-questions {
      display: flex;
      flex-wrap: wrap;
    }
  }
}
</style>
